package fm.admin.controller;

import com.mongodb.DBObject;
import fm.cache.AreaCache;
import fm.controller.BaseController;
import fm.dto.NeiyiUser;
import fm.entity.Address;
import fm.exception.BizException;
import fm.mongo.MCondition;
import fm.mongo.MRel;
import fm.mongoService.UserService;
import fm.util.CommonUtils;
import fm.util.DateUtils;
import fm.web.MediaTypes;
import fm.yichenet.mongo.service.ArticleService;
import fm.yichenet.mongo.service.MerchantService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by CM on 17/5/12.
 */
@Controller
@RequestMapping("/user/mgr")
public class UserMgrController extends BaseController {
    private static Logger LOGGER = LoggerFactory.getLogger(UserMgrController.class);
    @Autowired
    UserService userService;
    @Autowired
    fm.mongoService.UserService mongoUserService;

    @Autowired
    MerchantService merchantService;
    @Autowired
    ArticleService articleService;

    @RequestMapping("/index/{registerType}")
    public String index(ModelMap modelMap, @PathVariable Integer registerType
    ) throws Exception {
        Map<String, Object> params = new HashMap<>();
        LOGGER.info("===============" + registerType + "==================");
        params.put("userType", 3);
        modelMap.put("type", registerType);
        modelMap.put("shopUsers", mongoUserService.getByTypeAndUserId(params, 1, 10, ""));
        return "/admin/user/index";
    }
    @RequestMapping("/applay")
    public String applay() throws Exception {
        Map<String, Object> params = new HashMap<>();
        return "/admin/user/applay_mgr";
    }
    @RequestMapping("/updateinfo")
    public String updateinfo(ModelMap modelMap) throws Exception {
        modelMap.put("province", AreaCache.getAllProvince());
        return "/admin/user/updateinfo";
    }

    @ResponseBody
    @RequestMapping("/user/{id}")
    public Map getUserById(@PathVariable String id) {
        Map res = new HashMap();
        try {
            if (id == null) {
                throw new BizException("参数缺失!");
            }
            Object user = userService.getById(id);
            res.put("data", user);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }


    @ResponseBody
    @RequestMapping("/list/{userType}")
    public Map userList(Integer pageSize, Integer pageNum,
                        String shopId, Integer reviewStatus, String keyword,
                        String startTime, String endTime, @PathVariable(value = "userType") Integer userType) throws Exception {
        Map res = new HashMap();
        MCondition mc = MCondition.create(MRel.and);
        try {
//            if (!isAdmin()) {
//                shopId = getCurrentUserId();
//                mc.append("_id", shopId);
//            }
            long now = System.currentTimeMillis();
            if (reviewStatus != null) {
                mc.append("reviewStatus", reviewStatus);
            }
            if (StringUtils.isNotEmpty(keyword)) {
                MCondition keywordMc = MCondition.create(MRel.or);
                keyword = URLDecoder.decode(keyword, "UTF-8");
                keywordMc.append(MCondition.create(MRel.regex).append("companyName", Pattern.compile(keyword)));
                keywordMc.append(MCondition.create(MRel.regex).append("phone", Pattern.compile(keyword)));

                mc.append(keywordMc);
            }
            if (StringUtils.isNotEmpty(startTime)) {
                mc.append(MCondition.create(MRel.gte).append("regTime", DateUtils.StringToDate(startTime)));
            }
            if (StringUtils.isNotEmpty(endTime)) {
                mc.append(MCondition.create(MRel.lte).append("regTime", DateUtils.StringToDate(endTime)));
            }
            if (userType != 99) {
                mc.append("userType", userType);
            }
            List userList = mongoUserService.getByTypeAndUserId(mc.toDBObject().toMap(), pageSize, pageNum, "");
            long total = mongoUserService.countUser(mc.toDBObject().toMap());
            res.put("total", total);
            LOGGER.info("cost time : {}ms", System.currentTimeMillis() - now);
            res.put("data", userList);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    @ResponseBody
    @RequestMapping("/listwitharticle/{userType}")
    public Map getLogisticsShopList(Integer pageSize, Integer pageNum, Integer reviewStatus, @PathVariable(value = "userType") Integer userType,
                                    String cityId, String keyword) {
        Map res = new HashMap();
        List userWithArticle = new ArrayList();
        MCondition mc = MCondition.create(MRel.and);
        try {
            if (reviewStatus != null) {
                mc.append("reviewStatus", reviewStatus);
            }
            if (StringUtils.isNotEmpty(cityId)) {
                mc.append("userAdd.city", cityId);
            }
            if (StringUtils.isNotEmpty(keyword)) {
                mc.append(MCondition.create(MRel.regex).append("companyName", keyword));
            }
            if (userType != 99) {
                mc.append("userType", userType);
            }
            List<NeiyiUser> userList = mongoUserService.getByTypeAndUserId(mc.toDBObject().toMap(), pageSize, pageNum, "");
            long total = mongoUserService.countUser(mc.toDBObject().toMap());
            if (!userList.isEmpty()) {
                for (NeiyiUser user : userList) {
                    Map resmap = new HashMap();
                    Map params = new HashMap();
                    params.put("user_id", user.getId());
                    mc.append("user_id", user.getId());
                    List<DBObject> articles = articleService.getArticleForPage(params, 4, pageNum);
                    resmap.put("user", user);
                    resmap.put("info", articles);
                    userWithArticle.add(resmap);
                }
            }
            res.put("data", userWithArticle);
            res.put("total", total);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    @ResponseBody
    @RequestMapping("/authinfo")
    public Map getUserAuthInfo(String userId) {
        LOGGER.info(userId + "");
        Map res = new HashMap();
        try {
            if (userId == null) {
                throw new BizException("参数缺失！");
            }
            NeiyiUser user = mongoUserService.getUserAuthInfo(userId);
            res.put("data", user);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }


    @ResponseBody
    @RequestMapping("/authinfo/review")
    public Map reviewAuthInfo(String userId, Integer reviewStatus, String reviewNotes) {
        Map res = new HashMap();
        try {
            NeiyiUser user = mongoUserService.getUserAuthInfo(userId);
            if (user == null) {
                throw new BizException("未找到相关用户信息，审核失败!");
            }
            Map queryParam = new HashMap();
            queryParam.put("_id", userId);

            Map updateItem = new HashMap();
            updateItem.put("reviewStatus", reviewStatus);
            updateItem.put("reviewNote", reviewNotes);
            mongoUserService.updateUserInfo(queryParam, updateItem);
            res.put("data", user);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("occur business error", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("occur un-expected error", ex);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    @ResponseBody
    @RequestMapping("/update")
    public Map updateUserInfo(String id, String name, String src, String value) {
        LOGGER.info("id:{} name:{} value:{}", id, name, value);
        Map res = new HashMap();
        Map param = new HashMap();
        param.put("_id", id);
        Map updateItem = new HashMap();
        NeiyiUser neiyiUser = userService.getById(id);
        if (neiyiUser == null) {
            LOGGER.error("用户不存在", id);
            this.failed(res, "用户不存在！");
        } else {
            //写死配置4张图片，后续有需求可该改为参数配置
            if (CommonUtils.isEmpty(neiyiUser.getCompanyPics())) {
                neiyiUser.getCompanyPics().add(0, "");
                neiyiUser.getCompanyPics().add(1, "");
                neiyiUser.getCompanyPics().add(2, "");
                neiyiUser.getCompanyPics().add(3, "");
            }
            switch (name) {
                case "companyPics1":
                    neiyiUser.getCompanyPics().set(0, value);
                    updateItem.put("companyPics", neiyiUser.getCompanyPics());
                    break;
                case "companyPics2":
                    if (neiyiUser.getCompanyPics().size() < 2) {
                        neiyiUser.getCompanyPics().add(1, "");
                    }
                    neiyiUser.getCompanyPics().set(1, value);
                    updateItem.put("companyPics", neiyiUser.getCompanyPics());

                    break;
                case "companyPics3":
                    if (neiyiUser.getCompanyPics().size() < 3) {
                        neiyiUser.getCompanyPics().add(2, "");
                    }
                    neiyiUser.getCompanyPics().set(2, value);
                    updateItem.put("companyPics", neiyiUser.getCompanyPics());
                    break;
                case "companyPics4":
                    if (neiyiUser.getCompanyPics().size() < 4) {
                        neiyiUser.getCompanyPics().add(3, "");
                    }
                    neiyiUser.getCompanyPics().set(3, value);
                    updateItem.put("companyPics", neiyiUser.getCompanyPics());
                    break;
                default:
                    updateItem.put(name, value);
            }
        }
        try {
            int count = userService.updateUserInfo(param, updateItem);
            res.put("data", count);
            this.success(res);
        } catch (Exception e) {
            LOGGER.error("occur un-expected error", e);
            this.failed(res, "服务器发生未知错误，请稍后再试或者联系管理员解决！");
        }
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/getUserList", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public Map getUserList(Integer userType, String userId, String keyword, String provinceId, String cityId, String sort, Integer reviewStatus,
                           Integer pageNum, Integer pageSize) throws Exception {
        Map res = new HashMap();
        MCondition mc = MCondition.create(MRel.and);
        try {
            if (!CommonUtils.isEmpty(userType)) {
                mc.append("userType", userType);
            }
            if (!CommonUtils.isEmpty(userId)) {
                mc.append("_id", userId);
            }
            if (!CommonUtils.isEmpty(cityId)) {
                mc.append("userAdd.city", cityId);
            }
            if (!CommonUtils.isEmpty(provinceId)) {
                mc.append("userAdd.province", provinceId);
            }
            if (!CommonUtils.isEmpty(reviewStatus)) {
                mc.append("reviewStatus", reviewStatus);
            }
            if (!CommonUtils.isEmpty(keyword)) {
                mc.append(MCondition.create(MRel.regex).append("companyName", keyword));
            }else{
                mc.append(MCondition.create(MRel.regex).append("companyName", ""));
            }

            List<NeiyiUser> userList = userService.getByTypeAndUserId(mc.toDBObject().toMap(), pageSize, pageNum, sort);
            Long count = userService.countUser(mc.toDBObject().toMap());
            res.put("data", userList);
            res.put("total", count);
            this.success(res);
        } catch (BizException ex) {
            LOGGER.error("发生错误:", ex);
            this.failed(res, ex.getMessage());
        } catch (Exception ex) {
            LOGGER.error("发生异常", ex);
            this.failed(res, "服务器发生了未知的错误，请联系管理员或者开发者解决!");
        }
        return res;
    }
       @ResponseBody
        @RequestMapping(value = "delete",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
        public Map deleteUserById(String id){
            Map res = new HashMap();
            try{
                mongoUserService.deleteUserById(id);
                res.put("data","");
                this.success(res);
            }catch (BizException ex){
                LOGGER.error("发生错误:",ex);
                this.failed(res,ex.getMessage());
            }catch (Exception ex){
                LOGGER.error("发生异常",ex);
                this.failed(res,"服务器发生了未知的错误，请联系管理员或者开发者解决!");
            }
            return res;
        }
    @ResponseBody
    @RequestMapping(value = "/updateinfo",method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public Map userRegister(@RequestBody ModelMap modelMap){
        Map res = new HashMap();
        try{
            Map query = new HashMap();
            Map update = new HashMap();
            NeiyiUser user = (NeiyiUser) getCurrentUser();
            update.put("stName",(String) modelMap.get("stName"));
            user.setUserAdd((String)modelMap.get("province"),(String)modelMap.get("city"),(String)modelMap.get("town"),(String)modelMap.get("detailAdd"));
            update.put("userAdd",user.getUserAdd());
            Address province = AreaCache.getAddress((String) modelMap.get("province"));
            Address city = AreaCache.getAddress((String) modelMap.get("city"));
            Address town = AreaCache.getAddress((String) modelMap.get("town"));
            user.setUserAddressName(CommonUtils.isEmpty(province)?"":province.getName(), CommonUtils.isEmpty(city)?"":city.getName(),CommonUtils.isEmpty(town)?"":town.getName());
            update.put("userAddressName",user.getUserAddressName());
            List companyPics = new ArrayList();
            companyPics.add((String)modelMap.get("companyPics1"));
            companyPics.add((String)modelMap.get("companyPics2"));
            companyPics.add((String)modelMap.get("companyPics3"));
            companyPics.add((String)modelMap.get("companyPics4"));
            update.put("companyPics",companyPics);
            update.put("userContact",(String) modelMap.get("userContact"));
            update.put("userDsc",(String) modelMap.get("userDsc"));
            update.put("userLogo",(String) modelMap.get("logo_img"));
            update.put("firstUpdate",1);
            query.put("_id",user.getId());
            userService.updateUserInfo(query,update);
            res.put("data","");
            this.success(res);
        }catch (BizException ex){
            LOGGER.error("发生错误:",ex);
            this.failed(res,ex.getMessage());
        }catch (Exception ex){
            LOGGER.error("发生异常",ex);
            this.failed(res,"服务器发生了未知的错误，请联系管理员或者开发者解决!");
        }
        return res;
    }
}
